package com.vint.leetcode;

import java.util.Arrays;

/*
 * 1. done
 * 2. easy
 * 3.判断数独是否有效，空格用.表示
 */
public class Leetcode36 {
	public boolean isValidSudoku(char[][] board) {
		//line&row
		for(int i=0; i < 9; i++) {
			//line
			if(!isValidLine(board[i])){
				return false;
			}
			//row
			char[] row = new char[9];
			for(int j = 0; j < 9; j++) {
				row[j] = board[j][i];
			}
			if(!isValidLine(row)) {
				return false;
			}
		}

		//block
		for(int i = 0; i < 9; i += 3) {
			for(int j = 0; j < 9; j += 3) {
				if (!isValidBlock(board, i, j)) return false;
			}
		}
		return true;
	}

	public boolean isValidLine(char[] line) {
		boolean[] visited = new boolean[9];
		Arrays.fill(visited, false);
		for(char c : line) {
			if (c != '.') {
				if ( c - '1' < 0 || c - '9'> 0) {
					return false;
				}
				if(visited[c-'1']){
					return false;
				} else {
					visited[c - '1'] = true;
				}
			}

		}
		return true;
	}

	public boolean isValidBlock(char[][] line, int sl, int sc) {
		char[] block = new char[9];
		int tmp = 0;
		for(int i = sl; i < 3 + sl; i++) {
			for (int j = sc; j < 3 + sc; j++) {
				block[tmp++] = line[i][j];
			}
		}
		return isValidLine(block);
	}
    public static void main(String[] args) {
		Leetcode36 leetcode36 = new Leetcode36();
		char[] line = {'1','.','.','.','.','.','.','3','5','4'};
		System.out.println(leetcode36.isValidLine(line));
    }
  }
